package com.xxrl.shop.service;

import com.xxrl.shop.domain.Address;
import com.xxrl.shop.domain.User;
import com.xxrl.shop.repository.AddressRepository;
import com.xxrl.shop.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author mis
 */
@Service
public class AddressService {

    private final AddressRepository addressRepository;
    private final UserRepository userRepository;

    public AddressService(AddressRepository addressRepository, UserRepository userRepository) {
        this.addressRepository = addressRepository;
        this.userRepository = userRepository;
    }

    public void resetUserDefault(Long userId) {
        User user = userRepository.getOne(userId);
        Address address = addressRepository.findTopByUserAndIsDefault(user);
        if (address != null && address.getIsDefault()) {
            address.setIsDefault(false);
        }
    }

    public List<Address> findUserAddressList(Long userId) {
        return addressRepository.findAllByUser(new User(userId));
    }

    public Address find(Long id) {
        return addressRepository.getOne(id);
    }

    public void delete(Long  addressId) {
        addressRepository.delete(new Address(addressId));
    }

    public void save(Address address) {
        addressRepository.save(address);
    }

    public void edit(Long addressId, String receiver, String phone, String streetName, Boolean isDefault) {
        Address old = addressRepository.getOne(addressId);
        old.setReceiver(receiver);
        old.setPhone(phone);
        old.setStreetName(streetName);
        old.setIsDefault(isDefault);
        addressRepository.save(old);
    }

    public void add(Address address, Long userId) {
        address.setUser(new User(userId));
        addressRepository.save(address);
    }
}
